import logging

from sqlalchemy import text
from sqlalchemy.engine import URL
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine

from src.settings import PostgreSQLSettings

logger = logging.getLogger(__name__)


class DatabaseSession:
    def __init__(self, settings: PostgreSQLSettings):
        self.settings = settings
        self.engine = create_async_engine(
            URL.create(
                drivername="postgresql+asyncpg",
                username=settings.user,
                password=settings.password,
                host=settings.host,
                port=int(settings.port),
                database=settings.db,
            )
        )
        self.async_session = None

    async def connect(self):
        async with self.engine.begin() as conn:
            await conn.run_sync(lambda c: c.execute(text("SELECT 1")))
            logger.info("Connected to database successfully!")

    async def close(self):
        if self.async_session:
            await self.async_session.close()
            self.async_session = None

    async def get_session(self):
        if not self.async_session:
            self.async_session = AsyncSession(self.engine)
        return self.async_session
